package vip.kqsy.cloud.blog.server.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import vip.kqsy.cloud.blog.server.mapper.BlogCommentMapper;
import vip.kqsy.cloud.blog.server.pojo.dto.CommentAddDTO;
import vip.kqsy.cloud.blog.server.pojo.dto.ListCommentDTO;
import vip.kqsy.cloud.blog.server.pojo.entity.BlogComment;
import vip.kqsy.cloud.blog.server.pojo.vo.ListCommentVO;
import vip.kqsy.cloud.blog.server.service.BlogCommentService;
import vip.kqsy.cloud.core.web.res.ResPage;
import vip.kqsy.cloud.user.api.SysUserApi;
import vip.kqsy.cloud.user.api.dto.SysUserDTO;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 博客评论 服务实现类
 * </p>
 *
 * @author cenjunjie
 * @since 2023-05-03
 */
@Service
@RequiredArgsConstructor
public class BlogCommentServiceImpl extends ServiceImpl<BlogCommentMapper, BlogComment> implements BlogCommentService {

    private final SysUserApi sysUserApi;

    @Override
    public void add(CommentAddDTO dto) {
        BlogComment blogComment = BeanUtil.toBean(dto, BlogComment.class);
        blogComment.setCreateTime(LocalDateTime.now());
        save(blogComment);
    }

    @Override
    public ResPage<ListCommentVO> list(ListCommentDTO dto) {
        PageHelper.startPage(dto);
        List<BlogComment> list = lambdaQuery()
                .eq(BlogComment::getBlogId, dto.getBlogId())
                .isNull(BlogComment::getReplyId)
                .list();
        ResPage<BlogComment> of = ResPage.of(list);
        return of.convertListType(source -> {
            ListCommentVO target = BeanUtil.toBean(source, ListCommentVO.class);
            SysUserDTO sysUserDTO = sysUserApi.findById(source.getUserId()).orThrow();
            target.setNickname(sysUserDTO.getNickname());
            target.setAvatar(sysUserDTO.getAvatar());

            List<BlogComment> subList = lambdaQuery()
                    .eq(BlogComment::getBlogId, dto.getBlogId())
                    .eq(BlogComment::getReplyId, source.getId())
                    .list();
            List<ListCommentVO.Item> collect = subList.stream().map(item -> {
                ListCommentVO.Item item2 = BeanUtil.toBean(item, ListCommentVO.Item.class);
                SysUserDTO sysUserDTO2 = sysUserApi.findById(item.getUserId()).orThrow();
                item2.setNickname(sysUserDTO2.getNickname());
                return item2;
            }).collect(Collectors.toList());
            target.setSubList(collect);
            return target;
        });
    }
}
